<template>
  <h2>watch侦听器的改写</h2>
  <p>count: {{ count }}</p>
  <button @click="count++">btn</button>

  <hr />

  <p class="p1">obj: {{ obj }}</p>
  <button @click="fn">btn2</button>

  <hr />

  <p>num: {{ num }}</p>
  <button @click="num *= 2">btn3</button>

  <hr />

  <p>name1: {{ name1 }}</p>
  <p>name2: {{ name2 }}</p>
  <button @click="changeName">btn4</button>
</template>

<script>
// 使用watch也需要从vue结构watch函数
// watch函数有三个参数，第一个是需要监听的变量，第二个是回调函数，第三个是选项对象

// watchEffect相比于watch来说
// 进入页面可以自动执行一次
// 自动监听回调函数里面用到的所有变量, 可以同时监听多个变量的改变了
import { ref, watch, watchEffect } from "vue";

export default {
  setup() {
    const count = ref(1);
    watch(count, (val, oldVal) => {
      console.log("count改变了", val, oldVal);
    });

    const obj = ref({ a: 3, b: 4 });
    const fn = () => {
      obj.value.b++;
    };
    watch(
      obj,
      (value) => {
        console.log("obj改变了", value);
        console.log(document.querySelector(".p1").innerHTML);
      },
      {
        deep: true,
        // immediate: true,
        flush: "post",
      }
    );

    const num = ref(100);
    watchEffect(() => {
      console.log(num.value);
    });

    const name1 = ref("zhangsan");
    const name2 = ref("tom");

    const changeName = () => {
      // name1.value = "lisi";
      name2.value = "wangwu";
    };

    watch(
      [name1, () => name2.value],
      ([newName1, newName2], [oldName1, oldName2]) => {
        console.log(newName1, newName2);
        console.log(oldName1, oldName2);
      }
    );

    return {
      count,
      obj,
      fn,
      num,
      name1,
      name2,
      changeName,
    };
  },
};
</script>
